import escapeRegExp from '../helpers/escapeRegExp';

export default server => {
	const {
		app: {
			model: { News },
		},
	} = server;

	server.methods.registerGraphQLSchema({
		name: 'News',
		model: News,
		queryFields: {
			Pagination: 'pagination',
		},
		mutationFields: {
			CreateOne: 'createOne',
		},
		onPreAddFields(tc) {
			const {
				app: { schemaComposer, graphqlResolvers },
			} = server;

			tc.addRelation('isPublished', {
				resolver: () =>
					schemaComposer.createResolver({
						name: 'newsIsPublished',
						type: 'Boolean',
						args: {
							isDraft: 'Boolean',
							datetime: 'Date!',
						},
						resolve: async ({
							args: { isDraft, datetime },
							context: { request },
						}) => {
							return !isDraft && datetime.getTime() <= Date.now();
						},
					}),
				prepareArgs: {
					isDraft: source => source.isDraft,
					datetime: source => source.datetime,
				},
				projection: { isDraft: 1, datetime: 1 },
			});

			graphqlResolvers.Query.NewsPagination = graphqlResolvers.Query.NewsPagination.addFilterArg(
				{
					name: 'titleSearch',
					type: 'String',
					description: '标题正则模糊匹配',
					query: (query, value) => {
						query.title = {
							$regex: escapeRegExp(value.trim()),
							$options: 'i',
						};
					},
				}
			).addFilterArg({
				name: 'isPublished',
				type: 'Boolean',
				description: '已发布',
				query: (query, value) => {
					if (value) {
						query.isDraft = false;
						query.datetime = { $lt: new Date() };
					} else {
						query.$or = (query.$or || []).concat([
							{ isDraft: true },
							{ datetime: { $gt: new Date() } },
						]);
					}
				},
			});
		},
	});
};
